package com.guli.edu.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.exception.RRException;
import com.guli.edu.entity.Subject;
import com.guli.edu.mapper.SubjectMapper;
import com.guli.edu.service.SubjectService;
import com.guli.edu.util.ExcelImportUtil;
import com.guli.edu.vo.SubjectNode;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author jiangli
 * @since 2019-11-28
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {
    @Autowired
    private SubjectMapper subjectMapper;

    @Override
    @Transactional
    public List<String> batchImport(MultipartFile file) throws Exception {

        //错误消息列表
        List<String> errorMsg = new ArrayList<>();

        //创建工具类对象
        ExcelImportUtil excelHSSFUtil = new ExcelImportUtil(file.getInputStream());
        //获取工作表
        Sheet sheet = excelHSSFUtil.getSheet();

        int rowCount = sheet.getPhysicalNumberOfRows();
        if (rowCount <= 1) {
            errorMsg.add("请填写数据");
            return errorMsg;
        }

        for (int rowNum = 1; rowNum < rowCount; rowNum++) {

            Row rowData = sheet.getRow(rowNum);
            if (rowData != null) {// 行不为空

                //获取一级分类
                String levelOneValue = "";
                Cell levelOneCell = rowData.getCell(0);
                if (levelOneCell != null) {
                    levelOneValue = excelHSSFUtil.getCellValue(levelOneCell).trim();
                    if (StrUtil.isEmpty(levelOneValue)) {
                        errorMsg.add("第" + rowNum + "行一级分类为空");
                        continue;
                    }
                }

                //判断一级分类是否重复
                Subject subject = this.getByTitle(levelOneValue);
                String parentId = null;
                if (subject == null) {
                    //将一级分类存入数据库
                    Subject subjectLevelOne = new Subject();
                    subjectLevelOne.setTitle(levelOneValue);
                    subjectLevelOne.setSort(rowNum);
                    baseMapper.insert(subjectLevelOne);//添加
                    parentId = subjectLevelOne.getId();
                } else {
                    parentId = subject.getId();
                }

                //获取二级分类
                String levelTwoValue = "";
                Cell levelTwoCell = rowData.getCell(1);
                if (levelTwoCell != null) {
                    levelTwoValue = excelHSSFUtil.getCellValue(levelTwoCell).trim();
                    if (StrUtil.isEmpty(levelTwoValue)) {
                        errorMsg.add("第" + rowNum + "行二级分类为空");
                        continue;
                    }
                }
                //判断二级分类是否重复
                Subject subjectSub = this.getSubByTitle(levelTwoValue, parentId);
                Subject subjectLevelTwo = null;
                if (subjectSub == null) {
                    //将二级分类存入数据库
                    subjectLevelTwo = new Subject();
                    subjectLevelTwo.setTitle(levelTwoValue);
                    subjectLevelTwo.setParentId(parentId);
                    subjectLevelTwo.setSort(rowNum);
                    baseMapper.insert(subjectLevelTwo);//添加
                }
            }
        }

        return errorMsg;
    }

    @Override
    public List<SubjectNode> subjectList() {
        List<Subject> subjects = this.baseMapper.selectList(null);
        return subjects.stream().filter(e -> e.getParentId().equals("0")).map(e -> covert(e, subjects)).collect(Collectors.toList());
    }

    /**
     * 递归封装children属性
     * 当filter条件不满足时跳出递归
     */
    private SubjectNode covert(Subject subject, List<Subject> subjects) {
        SubjectNode node = new SubjectNode();
        BeanUtils.copyProperties(subject, node);
        List<SubjectNode> children = subjects.stream().filter(e -> e.getParentId().equals(subject.getId())).map(e -> covert(e, subjects)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }

    @Override
    public List<SubjectNode> subjectList2() {
        return subjectMapper.selectNestedListByParentId("0");
    }

    /**
     * 删除分类
     */
    @Override
    public Boolean deleteSubjectById(String id) {
        //判断当前分类下面是否有子分类
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<Subject>().eq(Subject::getParentId, id));
        if (count > 0) {
            return false;
        } else {
            //没有子分类才能删除
            int result = this.baseMapper.deleteById(id);
            return result > 0;
        }
    }

    @Override
    public boolean saveLevel(Subject subject) {
        if (StrUtil.isEmpty(subject.getParentId())) {
            Subject subjectLevelOne = this.getByTitle(subject.getTitle());
            if(subjectLevelOne == null){
                subject.setParentId("0");
                return this.save(subject);
            }
            return false;
        } else {
            Subject subjectLevelTwo = this.getSubByTitle(subject.getTitle(), subject.getParentId());
            if(subjectLevelTwo == null){
                return this.save(subject);
            }else{
                throw new RRException(20001, "类别已存在");
            }
        }

    }

    /**
     * 根据分类名称查询这个一级分类中否存在
     */
    private Subject getByTitle(String title) {

        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", "0");//一级分类
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据分类名称和父id查询这个二级分类中否存在
     */
    private Subject getSubByTitle(String title, String parentId) {

        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", parentId);
        return baseMapper.selectOne(queryWrapper);
    }
}
